import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, FindOptionsWhere } from 'typeorm';
import { Customer } from '../entities/customer.entity';

@Injectable()
export class CustomerService {
  constructor(
    @InjectRepository(Customer)
    private customerRepository: Repository<Customer>,
  ) {}

  async queryCustomers(params: {
    name?: string;
    phone?: string;
    page?: number;
    size?: number;
  }) {
    const { name, phone, page = 1, size = 10 } = params;
    const where: FindOptionsWhere<Customer> = { isDeleted: false };

    if (name) {
      where.name = Like(`%${name}%`);
    }
    if (phone) {
      where.phone = Like(`%${phone}%`);
    }

    const [customers, total] = await this.customerRepository.findAndCount({
      where,
      skip: (page - 1) * size,
      take: size,
      order: {
        createdAt: 'DESC',
      },
    });

    return {
      data: customers,
      total,
    };
  }
}
